package com.mall.biz;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.constant.PropertiesKey;
import com.mall.web.util.StringUtil;

/**
 * 图片上传的方法
 * 
 * @author Administrator
 *
 */
@Service
public class ImageUploadBizImpl {

	private Logger log = LoggerFactory.getLogger(ImageUploadBizImpl.class);

	@Autowired
	private PropertiesConfigure propertiesConfigure;

	public static String HTTP_XIE = "/";
	public static String HTTP_HENG = "-";

	/**
	 * 上传一张图片,返回图片的路径
	 * 
	 * @param file
	 * @param folder
	 * @return
	 */
	public  String uploadImage(MultipartFile file, String folder, HttpServletRequest request) {
		String uploadDir = getUploadDir() + HTTP_XIE + folder;

		File dir = new File(uploadDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		String mainPicFileName = file.getOriginalFilename();
		String imgName = getFileNameAddTime(mainPicFileName);
		File picUploadFile = new File(dir, imgName);
		try {
			file.transferTo(picUploadFile);
		} catch (IllegalStateException | IOException e) {
			log.error(e.getMessage());
		}

		return folder + HTTP_XIE + imgName;
	}

	/**
	 * 上传多张图片，返回图片的路径
	 * 
	 * @param files
	 * @param folder
	 * @return
	 */
	public String[] uploadmulityImage(MultipartFile[] files, String folder, HttpServletRequest request) {
		String[] imgPaths = new String[files.length];
		for (int i = 0; i < files.length; i++) {
			imgPaths[i] = uploadImage(files[i], folder, request);
		}
		return imgPaths;
	}
	
	//上传多张图片，返回图片的路径逗号隔开
	public String uploadmulityImageDatabase(MultipartFile[] files, String folder, HttpServletRequest request) {
		String[] imgPaths = new String[files.length];
		for (int i = 0; i < files.length; i++) {
			imgPaths[i] = uploadImage(files[i], folder, request);
		}
		return StringUtils.join(imgPaths, ","); 
	}

	// 获取上传图片路径
	private String getUploadDir() {
		return propertiesConfigure.getProperties(PropertiesKey.userfilepath);
	}

	public static String getFileNameAddTime(String fileName) {
		fileName = fileName.replaceAll(",", "");
		fileName = fileName.replaceAll("，", "");
		fileName = fileName.replaceAll("\\(", "");
		fileName = fileName.replaceAll("\\)", "");
		fileName = StringUtil.retainEnglishAndNumber(fileName);
		return System.currentTimeMillis() + HTTP_HENG + fileName + ".png";
	}
}
